from pdf2image import convert_from_path
from PIL import Image

def convert_pdf_to_png(pdf_path, output_path):
    # 将PDF转换为多个图像对象
    images = convert_from_path(pdf_path)

    # 计算总高度和最大宽度
    total_height = sum(image.height for image in images)
    max_width = max(image.width for image in images)

    # 创建一个足够大的画布
    canvas = Image.new('RGB', (max_width, total_height), 'white')

    # 将每个图像粘贴到画布上
    y_offset = 0
    for image in images:
        canvas.paste(image, (0, y_offset))
        y_offset += image.height

    # 保存为PNG
    canvas.save(output_path)

# 示例使用
pdf_file_path = 'C:/Users/yra/Desktop/MathVecCluster/data/pdf/2019年北京市中考数学试卷.pdf'  # 替换为你的PDF文件路径
output_png_path = 'C:/Users/yra/Desktop/MathVecCluster/data/image/2019年北京市中考数学试卷pdf2image.png'  # 输出PNG文件的路径
convert_pdf_to_png(pdf_file_path, output_png_path)

